//
//  ZPMineOrderViewController.m
//  ZPIOSEducation
//
//  Created by 李伟 on 2016/12/4.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPMineOrderViewController.h"
#import "ZPMyOrderTableViewCell.h"
#import "ZPMyOrderActionBarCell.h"
#import "ZPEmptyOrderView.h"

#import "OrderCreateViewController.h"
#import "ZPConfirmOrderViewController.h"
#import "MJRefresh.h"

@interface ZPMineOrderViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>
{
    ZPEmptyOrderView *emptyFooterView;
    NSMutableArray  *dataArray;
    
    NSInteger  currentPage;
    BOOL  hasNextPage;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation ZPMineOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的订单";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(navLeftButtonClick)];
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(refreshOrderList) name:@"refreshOrderList" object:nil];
    

    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    dataArray = [[NSMutableArray  alloc] init];
    currentPage = 1;
    hasNextPage = NO;
   
    __weak ZPMineOrderViewController *weakSelf = self;
    [self.mainTableView  addLegendHeaderWithRefreshingBlock:^{
        [weakSelf  refreshOrderList];
    }];
    
    [self.mainTableView  addLegendFooterWithRefreshingBlock:^{
        [weakSelf  loadMoreData];
    }];
    
    [self  requestData];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)loadMoreData
{
    if (hasNextPage) {
        [self  requestData];
    }else {
        [self.mainTableView.footer endRefreshing];
    }
}

- (void)refreshOrderList
{
    currentPage = 1;
    [self  requestData];
}

#pragma mark - 没有数据视图
- (void)showNoDataViewWithKeyWord:(NSString *)key
{
    
    if (emptyFooterView) {
        emptyFooterView.hidden = NO;
        [self.view bringSubviewToFront:emptyFooterView];
    } else {
        emptyFooterView = [[[NSBundle mainBundle] loadNibNamed:@"ZPEmptyOrderView" owner:self options:nil] lastObject];
        self.view = emptyFooterView;
    }
}

- (void)hideDataView
{
    if (emptyFooterView) {
        emptyFooterView.hidden = YES;
    }
}

#pragma mark - Button Actions
#pragma mark 导航栏左边按钮
- (void)navLeftButtonClick
{
    if (_isFromPaySuc) {
        [((UITabBarController *)self.view.window.rootViewController) setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:NO];
    }else{
    [self.navigationController popViewControllerAnimated:YES];    }

}

#pragma mark cell内状态按钮
- (void)cellStatusButtonClick:(id)sender
{
    UIButton  *tempBtn = (UIButton  *)sender;
    NSInteger  tag = tempBtn.tag;
    NSDictionary  *tempDic = [dataArray  objectAtIndex:tag];
    NSString  *statuStr = tempBtn.titleLabel.text;
    if ([statuStr  isEqualToString:@"去支付"]) {
        OrderCreateViewController  *viewController = [[OrderCreateViewController alloc] initWithNibName:@"OrderCreateViewController" bundle:nil];
        viewController.orderSn = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"orderSn"]];
        viewController.needPay = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"totalAmount"]];
        [self.navigationController  pushViewController:viewController animated:YES];
    }else if ([statuStr  isEqualToString:@"删除订单"]) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"删除订单后无法恢复，确认删除吗？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles: nil];
        actionSheet.tag = tag;
        [actionSheet showInView:self.view];
    }
}

#pragma mark -网络相关
#pragma mark 请求数据
- (void)requestData
{
    [self  showHudithString:@"加载中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId",@"10",@"pagesize",[NSString  stringWithFormat:@"%ld",(long)currentPage],@"pagenumber", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"centerorders/getorderlist.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if (self.mainTableView.header.isRefreshing) {
            [self.mainTableView.header  endRefreshing];
        }
        if (self.mainTableView.footer.isRefreshing) {
            [self.mainTableView.footer  endRefreshing];
        }
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if (currentPage == 1) {
                [dataArray  removeAllObjects];
            }
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"result"] isKindOfClass:[NSArray  class]]) {
                [dataArray  addObjectsFromArray:[[responseObject  objectForKey:@"result"] objectForKey:@"result"]];
            }
            [self.mainTableView  reloadData];
            
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"hasNextPage"] boolValue]) {
                currentPage ++;
                hasNextPage = YES;
            }else {
                hasNextPage = NO;
                [self.mainTableView.footer  noticeNoMoreData];
            }
            
            if (dataArray.count == 0) {
                [self  showNoDataViewWithTitle:@"暂无相关订单~"];
            }else {
                [self  hiddenNoDataView];
            }
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        if (self.mainTableView.header.isRefreshing) {
            [self.mainTableView.header  endRefreshing];
        }
        if (self.mainTableView.footer.isRefreshing) {
            [self.mainTableView.footer  endRefreshing];
        }
    }];
}

#pragma mark 删除订单
- (void)deleteOrderWithIndex:(NSInteger)index
{
    [self  showHudithString:@"发送中..."];
    NSString  *orderSn = [[dataArray  objectAtIndex:index] objectForKey:@"orderSn"];
    
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId",[NSString stringWithFormat:@"%@",orderSn],@"orderSn", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"centerorders/deleteOrder.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                [dataArray  removeObjectAtIndex:index];
                [self.mainTableView  reloadData];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [dataArray  count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary  *tempDic = [dataArray  objectAtIndex:section];
    NSInteger  orderStatus = [[tempDic  objectForKey:@"orderStatus"] integerValue];
    if (orderStatus == 1 || orderStatus == 2 || orderStatus == 3) {
        return 2;
    }else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 8.;
}

- (UIView  *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView  *tempView = [[UIView  alloc] init];
    tempView.backgroundColor = [UIColor  clearColor];
    return tempView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 116.;
    }else {
        return 51.;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = [indexPath section];
    NSInteger row     = [indexPath row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:section];
    NSInteger  orderStatus = [[tempDic  objectForKey:@"orderStatus"] integerValue];
    
    if (row == 0) {
        static NSString *CellIdentifier = @"ZPMyOrderTableViewCell";
        ZPMyOrderTableViewCell  *cell = (ZPMyOrderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPMyOrderTableViewCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.orderDate.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"orderTime"]];
        cell.orderPayState.textColor = RGBACOLOR(153, 153, 153, 1.);
        switch (orderStatus) {
            case 0:
                cell.orderPayState.text = @"待审核";
                break;
            case 1:
                cell.orderPayState.text = @"已完成";
                break;
            case 2:
                cell.orderPayState.text = @"已取消";
                break;
            case 3:
                cell.orderPayState.text = @"待付款";
                cell.orderPayState.textColor = RGBACOLOR(255, 86, 86, 1.);
                break;
                
            default:
                cell.orderPayState.text = @"";
                break;
        }
        
        [cell.orderIcon  sd_setImageWithURL:[NSURL  URLWithString:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"teacherUrl"]]] placeholderImage:[UIImage  imageNamed:@"headportrait"]];
        cell.orderClassName.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"className"]];
        cell.orderClassNumber.text = [NSString  stringWithFormat:@"%@次课",[tempDic  objectForKey:@"courseNum"]];
        cell.orderClassFee.text = [NSString  stringWithFormat:@"￥%@",[tempDic  objectForKey:@"totalAmount"]];
        
        
        return cell;
    }else {
        static NSString *CellIdentifier = @"ZPMyOrderActionBarCell";
        ZPMyOrderActionBarCell  *cell = (ZPMyOrderActionBarCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPMyOrderActionBarCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.statusBtn.tag = section;
        if (orderStatus == 3) {
            [cell.statusBtn  setTitle:@"去支付" forState:UIControlStateNormal];
            [cell.statusBtn  setBackgroundColor:RGBACOLOR(255, 86, 86, 1.)];
        }else {
            [cell.statusBtn  setTitle:@"删除订单" forState:UIControlStateNormal];
            [cell.statusBtn  setBackgroundColor:RGBACOLOR(33, 164, 235, 1.)];
        }
        [cell.statusBtn  addTarget:self action:@selector(cellStatusButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  section = [indexPath  section];
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:section];
    if (row == 0) {
        ZPConfirmOrderViewController  *viewController = [[ZPConfirmOrderViewController  alloc] initWithNibName:@"ZPConfirmOrderViewController" bundle:nil];
        viewController.orderSn = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"orderSn"]];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self  deleteOrderWithIndex:actionSheet.tag];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:@"refreshOrderList" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
